import { checkBindMobile, getSmsCode, updateMemberPhone, checkSmsCode, checkPhoneCode } from '../../api/member'
import Validate from '../../common/validator/index'
import { notEmpty, isMobile } from '../../common/validator/rules'
import { _debounce } from '@src/common/utils'
import $cache from "@src/common/wxCache";
import router from '@src/router';
const themeConfigMall = $cache.get('themeConfig-mall') || {}
const extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
import { getMercFlowConsume, getRemindFlag } from "@src/api/marketing"
// 验证码倒计时
const SMSWAIT = 60

function initCheckPhone() {
    let timer = setTimeout(async () => {
        const RemindFlagRes = await getRemindFlag({ businessId: extConfig.businessId })
        if (RemindFlagRes.data) return wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data,
            success: function (res) {
                wx.exitMiniProgram()
            }
        })
        let merphone = $cache.get("base_info").phone
        const mercRes = await getMercFlowConsume({
            phone: merphone ? merphone : '',
            appId: extConfig.appId
        })
        if (mercRes.data) return wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data,
            success: function (res) {
                wx.exitMiniProgram()
            }
        })

        this.data.login && await this.getBaseInfo()
        const themeConfigMall = $cache.get('themeConfig-mall') || {}
        const { businessId, phone, customId, storeNo, xsOpenId, memberStatus } = getApp().globalData.extraData || {}
        const appOps = wx.getEnterOptionsSync()
        const result = await checkMemberMobile({
            data: {
                phone: phone || null,
                businessId: (~~businessId) || (~~extConfig.businessId) || null, // 存在0的id
                customId: (~~customId) || null,
                mercNo: storeNo || null,
                xsOpenId: (phone && appOps.scene === 1037) ? (xsOpenId || null) : null,
                status: phone ? ~~memberStatus : null
            },
            header: {
                xhOpenId: this.data.xhOpenId || null,
                mercNo: themeConfigMall.mercNo
            }
        });
        this.setData({ loading: false })
        if (result && result.type === 'alreadyExists') return wx.showModal({
            title: '提示',
            showCancel: false,
            content: '您已经是会员，无需再开卡',
            success: () => {
                wx.exitMiniProgram()
            }
        })
        this.phone = phone
        console.log(result.type, 111)
        result && this.setData({
            bindType: result.type,
            member: result.member,
            showPopup: result.type === 'openIdBindDifferentPhone' || result.type === 'phoneBindDifferentOpenId',
            smsPhone: phone ? this.filterMobile(phone) : ''
        }, () => {
            if (this.data.login && result.type === "directOpenCard") {
                this.autoOPenCard()
            }
            if (!this.data.login && (result.type === 'openIdBindDifferentPhone' || result.type === 'phoneBindDifferentOpenId')) {
                this.selectComponent("#login").requireLogin()
            }
            // 如果是需要发验证码的，立即发送验证码
            if (result.type === 'openIdBindDifferentPhone' || result.type === 'phoneBindDifferentOpenId') {
                this.handleSmsCode()
            }
            if (result.type === 'updateOriginMemberPhone') {
                this.updateUserPhone()
            }
        })
        clearTimeout(timer)
        timer = null
    }, 800)
}

// 判断是否绑定开卡手机号
const checkMemberMobile = (params) => {
    return new Promise((resolve, reject) => {
        // 没有捕获异常
        checkBindMobile(params)
            .then(({ code, data }) => {
                if (code === 0) {
                    resolve(data)
                } else {
                    reject(null)
                }
            })
    })
}

// 阻止滑动穿透
function clear() {
    return
}

function filterMobile(mobile) {
    const validator = new Validate({ notEmpty, isMobile });
    validator.add(mobile, [{ strategy: 'notEmpty', errorMsg: '手机号码不能为空' }, { strategy: 'isMobile', errorMsg: '手机号码格式不正确' }])
    const validateRes = validator.validate();
    if (validateRes) return this.setData({ showPopup: false }, () => wx.showToast({ title: validateRes, icon: 'none' }))
    return String(mobile).replace(/(\d{3})\d{4}(\d{4})/, "$1****$2")
}

// 验证码
const handleSms = _debounce(function () {
    this.setData({
        showPopup: true
    })
}, 250)

// 获取验证码
const handleSmsCode = _debounce(function () {
    if (this.waiting) return
    this.waiting = true
    const phone = this.phone
    if (!phone) return wx.showToast({ title: 'phone不能为空' })
    getSmsCode(phone)
        .then(res => {
            const { phoneCode } = JSON.parse(res.data)
            let wait = SMSWAIT
            this.setData({
                smsText: `${wait}s`,
                phoneCode
            })
            let timer = setInterval(() => {
                wait--
                if (wait < 0) {
                    this.setData({
                        smsText: '重新获取'
                    })
                    wait = SMSWAIT
                    this.waiting = false
                    clearInterval(timer)
                    timer = null
                } else {
                    this.setData({
                        smsText: `${wait}s`
                    })
                }
            }, 1000)
        })
}, 250)

// 输入验证码
const onInputSms = _debounce(function (e) {
    this.setData({
        smsCode: e.detail.value
    })
}, 250)

const handleCheckSms = _debounce(async function () {
    const { bindType, smsCode, phoneCode, member, isMember } = this.data
    const miniProgram = $cache.get('miniProgram') || {}
    const params = {
        phone: this.phone,
        type: bindType ? bindType : '',
        phoneCode: smsCode,
        businessId: extConfig.businessId || null,
        xsOpenId: miniProgram.xsOpenId || null
    }
    if (miniProgram.storeNo) { // 多余的
        params.customId = ~~miniProgram.customId
        params.mercNo = miniProgram.storeNo || null
        params.status = ~~miniProgram.memberStatus
    }
    const validator = new Validate({ notEmpty, isMobile });
    validator.add(params.phone, [{ strategy: 'notEmpty', errorMsg: '手机号码不能为空' }, { strategy: 'isMobile', errorMsg: '手机号码格式不正确' }])
    validator.add(params.type, [{ strategy: 'notEmpty', errorMsg: 'type不能为空' }])
    validator.add(params.phoneCode, [{ strategy: 'notEmpty', errorMsg: '验证码不能为空' }])
    validator.add(params.businessId, [{ strategy: 'notEmpty', errorMsg: 'businessId不能为空' }])

    const errorMsg = validator.validate()
    if (errorMsg) return wx.showToast({ title: errorMsg, icon: 'none' })
    if (!phoneCode) return wx.showToast({ title: '请获取验证码', icon: 'none' })
    if ((+smsCode) !== phoneCode) return wx.showToast({ title: '手机验证码错误', icon: 'none' })
    try {
        const { code } = await checkPhoneCode({ data: { "phoneCode": (+smsCode), "phone": this.phone } })
        if (code !== 0) return
        this.setData({
            smsText: '获取验证码',
            isPassCode: true,
            showPopup: false
        })
        const header = {
            xhOpenId: this.data.xhOpenId || null,
            mercNo: themeConfigMall.mercNo
        }
        if (member || isMember) {
            const { code: bindCode } = await checkSmsCode({ data: params, header })
            if (bindCode === 0) {
                wx.showToast({
                    title: '更新成功',
                    success: () => {
                        setTimeout(() => {
                            const appOps = wx.getEnterOptionsSync()
                            const isNavMini = getApp().globalData.isNavMini
                            if (appOps.scene === 1037) {
                                wx.navigateBackMiniProgram()
                            }
                        }, 1500);
                    }
                })
                // wx.showModal({
                //     title: '更新成功',
                //     showCancel: false,
                //     success: () => {
                //         const appOps = wx.getEnterOptionsSync()
                //         const isNavMini = getApp().globalData.isNavMini
                //         if (isNavMini || appOps.scene === 1037) {
                //             wx.exitMiniProgram()
                //         }
                //     }
                // })

            }
        } else {
            wx.showToast({
                title: '验证码正确',
                icon: 'none',
                success: () => {
                    setTimeout(() => {
                        this.autoOPenCard()
                    }, 1500)
                }
            })
            
        }

    } catch (error) {
        console.error(error)
    }

    // checkSmsCode({
    //     data: params,
    //     header: {
    //         xhOpenId: this.data.xhOpenId || null,
    //         mercNo: themeConfigMall.mercNo
    //     }
    // })
    //     .then(res => {
    //         // 待成功处理
    //         if(res.code === 0) {
    //             const { member } = this.data
    //             this.setData({
    //                 smsText: '获取验证码',
    //                 showPopup: false
    //             })
    //             if(!member) {
    //                 this.handleNewOpenCard()
    //             } else {
    //                 wx.showModal({
    //                     title: '提示',
    //                     showCancel: false,
    //                     content: res.data,
    //                     success:  ()  => {
    //                         const appOps = wx.getEnterOptionsSync()
    //                         if(appOps.scene === 1037) {
    //                             wx.exitMiniProgram()
    //                         } else {
    //                             router.push({
    //                                 name: 'index'
    //                             })
    //                         }

    //                     }
    //                 })
    //             }
    //         } 
    //     })
    //     .catch(err => {
    //         console.log(err)
    //     })
}, 250)

function updateUserPhone() {
    const _themeConfigMall = $cache.get('themeConfig-mall')
    if (_themeConfigMall) {
        updatePhoneCom.call(this)
    } else {
        base.themeConfig(updatePhoneCom.call(this))
    }
}

function updatePhoneCom() {
    let timer = setTimeout(() => {
        const _themeConfigMall = $cache.get('themeConfig-mall')
        const miniProgram = $cache.get('miniProgram')
        const { bindType } = this.data

        const params = {
            phone: this.phone,
            type: bindType ? bindType : '',
            businessId: extConfig.businessId || null,
            // 这下面理应不用的，后端让加的，额外添加一个读取io
            xsOpenId: miniProgram.xsOpenId || null,
            customId: ~~miniProgram.customId,
            mercNo: miniProgram.storeNo || null,
            status: ~~miniProgram.memberStatus
        }
        console.log(params)
        updateMemberPhone({
            data: params,
            header: {
                xhOpenId: this.data.xhOpenId || null,
                mercNo: miniProgram.storeNo || _themeConfigMall.mercNo
            }
        })
            .then(res => {
                console.log('updatePhone =========')
                console.log(res)
                // 待成功处理
                if (res.code === 0) {
                    wx.showToast({
                        title: '更新成功',
                        success: () => {
                            setTimeout(() => {
                                const appOps = wx.getEnterOptionsSync()
                                if (appOps.scene === 1037) {
                                    wx.navigateBackMiniProgram()
                                } else {
                                    router.push({
                                        name: 'index'
                                    })
                                }
                            }, 1500);
                        }
                    })
                }
            })
            .catch(err => {
                setTimeout(timer)
                timer = null
                console.log(err)
            })
        setTimeout(timer)
        timer = null
    }, 500)
}

export default {
    initCheckPhone,
    checkMemberMobile,
    clear,
    filterMobile,
    handleSms,
    handleSmsCode,
    onInputSms,
    handleCheckSms,
    updateUserPhone
}